const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const ConfigManager = require('./config-manager');
const PluginManager = require('./plugins/core/manager');
const { loadPlugins } = require('./plugins/loader');

let mainWindow;
let configManager;

function createWindow(config) {
  const windowConfig = config.window;
  
  mainWindow = new BrowserWindow({
    width: windowConfig.width || 1200,
    height: windowConfig.height || 800,
    x: windowConfig.x,
    y: windowConfig.y,
    show: false, // 初始不显示窗口
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  // 在开发环境下使用Vite开发服务器，生产环境下使用本地文件
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173');
  } else {
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));
  }

  // 等待页面加载完成后显示窗口，避免白屏闪烁
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  // mainWindow.webContents.openDevTools();

}

app.on('ready', async () => {
  // 初始化配置管理器
  configManager = new ConfigManager();
  await configManager.createDefaultConfig();
  
  // 获取配置
  const config = await configManager.getConfig();
  
  // 初始化插件管理器
  const pluginManager = new PluginManager();
  
  // 加载插件
  const pluginsDir = path.join(__dirname, '../../plugins');
  await loadPlugins(pluginsDir, pluginManager);
  
  // 创建主窗口
  createWindow(config);
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', async () => {
  if (mainWindow === null) {
    const config = await configManager.getConfig();
    createWindow(config);
  }
});

// IPC Example
ipcMain.on('message', (event, message) => {
  console.log('Received message:', message);
  event.reply('reply', `Main process received: ${message}`);
});

// 获取配置
ipcMain.handle('config-get', async (event, key) => {
  try {
    const config = await configManager.getConfig(key);
    return { success: true, data: config };
  } catch (error) {
    console.error('获取配置失败:', error);
    return { success: false, error: error.message };
  }
});

// 更新配置
ipcMain.handle('config-update', async (event, updates) => {
  try {
    const newConfig = await configManager.updateConfig(updates);
    return { success: true, data: newConfig };
  } catch (error) {
    console.error('更新配置失败:', error);
    return { success: false, error: error.message };
  }
});

// 重置配置
ipcMain.handle('config-reset', async () => {
  try {
    await configManager.createDefaultConfig();
    const config = await configManager.getConfig();
    return { success: true, data: config };
  } catch (error) {
    console.error('重置配置失败:', error);
    return { success: false, error: error.message };
  }
});

// 获取配置路径
ipcMain.handle('get-config-path', async () => {
  return {
    configDir: configManager.getConfigDir(),
    configFile: configManager.getConfigPath()
  };
});

// 选择文件夹
ipcMain.handle('select-folder', async () => {
  try {
    const { dialog } = require('electron');
    const result = await dialog.showOpenDialog(mainWindow, {
      properties: ['openDirectory'],
      title: '选择默认文件保存路径'
    });
    
    if (!result.canceled && result.filePaths.length > 0) {
      return { success: true, path: result.filePaths[0] };
    }
    
    return { success: false, path: '' };
  } catch (error) {
    console.error('选择文件夹失败:', error);
    return { success: false, error: error.message };
  }
});

// 处理文件创建请求
ipcMain.handle('create-file', async (event, filePath, content) => {
  try {
    const fs = require('fs').promises;
    const path = require('path');
        
    // 检查文件是否已存在
    try {
      await fs.access(filePath);
      return { success: false, error: '文件已存在' };
    } catch (err) {
      // 文件不存在，继续创建
    }
    
    // 确保目录存在
    const dir = path.dirname(filePath);
    await fs.mkdir(dir, { recursive: true });
    
    // 创建文件
    await fs.writeFile(filePath, content, 'utf8');
    console.log(`文件创建成功: ${filePath}`);
    
    return { success: true, path: filePath };
  } catch (error) {
    console.error('创建文件失败:', error);
    return { success: false, error: error.message };
  }
});

// 读取目录下的文件列表
ipcMain.handle('read-directory', async (event, dirPath) => {
  try {
    const fs = require('fs').promises;
    const path = require('path');
    
    // 读取目录内容
    const files = await fs.readdir(dirPath);
    
    // 过滤出文件（排除目录）
    const fileList = [];
    for (const file of files) {
      const filePath = path.join(dirPath, file);
      const stats = await fs.stat(filePath);
      if (stats.isFile()) {
        fileList.push(file);
      }
    }
    
    return { success: true, files: fileList };
  } catch (error) {
    console.error('读取目录失败:', error);
    return { success: false, error: error.message };
  }
});

// 读取文件的第一行
ipcMain.handle('read-file-first-line', async (event, filePath) => {
  try {
    const fs = require('fs').promises;
    
    // 读取文件内容
    const content = await fs.readFile(filePath, 'utf8');
    
    // 获取第一行（去除前后空白）
    const lines = content.split('\n');
    const firstLine = lines[0]?.trim() || '';
    
    // 如果是Markdown标题，去掉#号
    const displayName = firstLine.replace(/^#+\s*/, '') || '未命名文档';
    
    return { success: true, firstLine: displayName };
  } catch (error) {
    console.error('读取文件失败:', error);
    return { success: false, error: error.message, firstLine: '读取失败' };
  }
});

// 读取整个文件内容
ipcMain.handle('read-file', async (event, filePath) => {
  try {
    const fs = require('fs').promises;
    const content = await fs.readFile(filePath, 'utf8');
    return { success: true, content };
  } catch (error) {
    console.error('读取文件失败:', error);
    return { success: false, error: error.message, content: '' };
  }
});

// 保存文件内容
ipcMain.handle('save-file', async (event, filePath, content) => {
  try {
    const fs = require('fs').promises;
    const path = require('path');
    
    // 确保目录存在
    const dir = path.dirname(filePath);
    await fs.mkdir(dir, { recursive: true });
    
    // 写入文件内容
    await fs.writeFile(filePath, content, 'utf8');
    console.log(`文件保存成功: ${filePath}`);
    
    return { success: true, path: filePath };
  } catch (error) {
    console.error('保存文件失败:', error);
    return { success: false, error: error.message };
  }
});

// 获取文件状态信息
ipcMain.handle('get-file-stats', async (event, filePath) => {
  try {
    const fs = require('fs').promises;
    const stats = await fs.stat(filePath);
    
    return { 
      success: true, 
      stats: {
        size: stats.size,
        mtime: stats.mtime,
        birthtime: stats.birthtime,
        isFile: stats.isFile(),
        isDirectory: stats.isDirectory()
      }
    };
  } catch (error) {
    console.error('获取文件状态失败:', error);
    return { success: false, error: error.message };
  }
});

// 删除文件
ipcMain.handle('delete-file', async (event, filePath) => {
  try {
    const fs = require('fs').promises;
    await fs.unlink(filePath);
    console.log(`文件删除成功: ${filePath}`);
    return { success: true };
  } catch (error) {
    console.error('删除文件失败:', error);
    return { success: false, error: error.message };
  }
});
